import * as vscode from 'vscode';
import { ApiClient, CompletionItem, CompletionRequest, CodeContext } from '../utils/apiClient';

export class CompletionProvider implements vscode.CompletionItemProvider {
    private apiClient: ApiClient;

    constructor(apiClient: ApiClient) {
        this.apiClient = apiClient;
    }

    async provideCompletionItems(
        document: vscode.TextDocument,
        position: vscode.Position,
        token: vscode.CancellationToken,
        context: vscode.CompletionContext
    ): Promise<vscode.CompletionItem[] | vscode.CompletionList | undefined> {
        try {
            // 检查是否应该提供补全
            if (token.isCancellationRequested) {
                return undefined;
            }

            // 构建代码上下文
            const codeContext = this.buildCodeContext(document, position);
            
            // 构建补全请求
            const completionRequest: CompletionRequest = {
                context: codeContext,
                maxResults: 10,
                useLLM: true,
                includeSnippets: true,
                timeout: 5000
            };

            // 根据文件类型选择不同的补全服务
            let completionItems: CompletionItem[];
            if (document.fileName.endsWith('.gn')) {
                completionItems = await this.apiClient.getGnCompletions(completionRequest);
            } else {
                completionItems = await this.apiClient.getCompletions(completionRequest);
            }

            // 转换为VSCode补全项
            const vscodeItems = completionItems.map(item => this.convertToVscodeCompletionItem(item));

            return new vscode.CompletionList(vscodeItems, false);

        } catch (error) {
            console.error('提供代码补全时出错:', error);
            return undefined;
        }
    }

    private buildCodeContext(document: vscode.TextDocument, position: vscode.Position): CodeContext {
        const filePath = document.fileName;
        const code = document.getText();
        const cursorLine = position.line;
        const cursorColumn = position.character;
        
        // 获取光标前后的代码
        const lines = code.split('\n');
        const prefixLines = lines.slice(0, cursorLine);
        const suffixLines = lines.slice(cursorLine);
        
        const prefix = prefixLines.join('\n');
        const suffix = suffixLines.join('\n');
        
        // 检测语言类型
        let language = 'cpp';
        if (filePath.endsWith('.c')) {
            language = 'c';
        } else if (filePath.endsWith('.gn')) {
            language = 'gn';
        }

        // 获取项目根路径
        const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
        const projectRoot = workspaceFolder ? workspaceFolder.uri.fsPath : '';

        // 解析包含的头文件
        const includes = this.extractIncludes(code);

        // 解析命名空间和类名
        const { namespace, className, functionName } = this.parseCodeContext(code, cursorLine);

        return {
            filePath,
            code,
            cursorLine,
            cursorColumn,
            prefix,
            suffix,
            language,
            projectRoot,
            includes,
            namespace,
            className,
            functionName
        };
    }

    private extractIncludes(code: string): string[] {
        const includeRegex = /#include\s*[<"]([^>"]+)[>"]/g;
        const includes: string[] = [];
        let match;
        
        while ((match = includeRegex.exec(code)) !== null) {
            includes.push(match[1]);
        }
        
        return includes;
    }

    private parseCodeContext(code: string, cursorLine: number): { namespace?: string; className?: string; functionName?: string } {
        const lines = code.split('\n');
        let namespace: string | undefined;
        let className: string | undefined;
        let functionName: string | undefined;

        // 查找命名空间
        for (let i = 0; i < Math.min(cursorLine, lines.length); i++) {
            const line = lines[i].trim();
            const namespaceMatch = line.match(/namespace\s+(\w+)/);
            if (namespaceMatch) {
                namespace = namespaceMatch[1];
            }
        }

        // 查找类名
        for (let i = 0; i < Math.min(cursorLine, lines.length); i++) {
            const line = lines[i].trim();
            const classMatch = line.match(/class\s+(\w+)/);
            if (classMatch) {
                className = classMatch[1];
            }
        }

        // 查找函数名
        for (let i = 0; i < Math.min(cursorLine, lines.length); i++) {
            const line = lines[i].trim();
            const functionMatch = line.match(/(\w+)\s*\([^)]*\)\s*{/);
            if (functionMatch) {
                functionName = functionMatch[1];
            }
        }

        return { namespace, className, functionName };
    }

    private convertToVscodeCompletionItem(item: CompletionItem): vscode.CompletionItem {
        const vscodeItem = new vscode.CompletionItem(item.label);
        
        vscodeItem.detail = item.detail;
        vscodeItem.documentation = item.documentation;
        vscodeItem.insertText = new vscode.SnippetString(item.insertText);
        vscodeItem.sortText = item.sortOrder?.toString() || '0';
        
        // 设置补全类型
        switch (item.kind) {
            case 'function':
                vscodeItem.kind = vscode.CompletionItemKind.Function;
                break;
            case 'class':
                vscodeItem.kind = vscode.CompletionItemKind.Class;
                break;
            case 'variable':
                vscodeItem.kind = vscode.CompletionItemKind.Variable;
                break;
            case 'keyword':
                vscodeItem.kind = vscode.CompletionItemKind.Keyword;
                break;
            case 'method':
                vscodeItem.kind = vscode.CompletionItemKind.Method;
                break;
            case 'property':
                vscodeItem.kind = vscode.CompletionItemKind.Property;
                break;
            case 'enum':
                vscodeItem.kind = vscode.CompletionItemKind.Enum;
                break;
            case 'interface':
                vscodeItem.kind = vscode.CompletionItemKind.Interface;
                break;
            default:
                vscodeItem.kind = vscode.CompletionItemKind.Text;
        }

        // 设置优先级
        if (item.confidence) {
            vscodeItem.sortText = (100 - item.confidence * 100).toString().padStart(3, '0');
        }

        return vscodeItem;
    }
}
